package com.leo.chapter15;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 非阻塞的栈
 * @author xuexiaolei
 * @version 2017年10月20日
 */
public class ConcurrentStack<E> {
    AtomicReference<Node<E>> top = new AtomicReference<>();

    public void push(E item){
        Node<E> newNode = new Node<>(item);
        Node<E> oldNode;
        do {
            oldNode = top.get();
            newNode.next = oldNode;
        }while (!top.compareAndSet(oldNode, newNode));
    }

    public E pop(){
        Node<E> newNode, oldNode;
        do {
            oldNode = top.get();
            if (oldNode == null){
                return null;
            }
            newNode = oldNode.next;
        }while (!top.compareAndSet(newNode, oldNode));
        return oldNode.item;
    }

    private static class Node<E>{
        public final E item;
        public Node<E> next;

        private Node(E item) {
            this.item = item;
        }
    }
}
